package com.letv.android.client.webview;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.WebBackForwardList;
import android.webkit.WebView;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.letv.android.young.client.R;
import com.letv.android.client.activity.WrapActivity;
import com.letv.android.client.view.PublicLoadLayout;
import com.letv.core.constant.PlayConstant;
import com.letv.core.db.PreferencesManager;
import com.letv.core.utils.LetvUtils;
import com.letv.core.utils.LogInfo;
import com.letv.core.utils.NetworkUtils;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 所有使用WebView的Activity的基类 Created by liuxingxing on 14-8-1.
 * 1.back按钮的业务逻辑不一样
 * 2.LetvWebViewClient中的业务逻辑不一样
 * 注意：子类在一般情况下主要写LetvWebViewClient的实现即可
 */
public class LetvBaseWebViewActivity extends WrapActivity implements View.OnClickListener {
    public static final int WEBVIEWREQUESTCODE = 1;
    public static final int WEBVIEWRESULTCODE = 2;
    public static final int goToLoginPageForJS = 1000;// JS调登录页面的forWhat
    public static final int goToLoginPageForMatchUrl = 1001;// 匹配url调登录页面的forWhat
    public static final int Login_OK = 12345;
    public static final int LOADURL = 0;
    public static int netType = -1;
    protected WebView mWebView;
    protected String baseUrl;
    protected ImageView getMoreImg;
    protected ProgressBar progressBar;
    protected TextView titleView;
    protected TextView urlTitleView;
    protected String loadType;
    protected ImageView close;
    protected boolean isFinish;
    private boolean isNeedStatistics;
    protected ImageView back_iv;
    protected PublicLoadLayout root;
    private LetvWebViewChromeClient webChromeClient;
    protected boolean flag = true;// 显示错误页面为false
//    private InviteShareFragment shareDialogFragment = null;
//    WebShareFragment mShareNewFragment = null;
    protected TextView pullDownUrlText;
    protected Activity mActivity = this;
    protected boolean mFlagErrorpagebycookie = true;// ture：因为没有同步成功显示错误页面，用来区别加载H5失败的原因
    private View topBar;
    private NetWorkBroadcastReceiver mNetWorkBroadcastReceiver = null;
    volatile boolean loadFinish = false;
    /**
     * 分享缺省标题
     */
    String mShareDefaultTitle = "";
    /**
     * 分享缺省图片
     */
    String mShareDefaultIcon = "";

    protected Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg != null && msg.arg1 == LOADURL) {
                String url = msg.getData().getString("url");
                loadUrlBySync(url);
            }
        }
    };

    /**
     * 此方法提供给子类用，若子类需要统计，那么须在此父类的onCreate()方法之前调用此方法设置
     * 
     * @param isNeedStatistics 是否需要统计
     */
    public void setNeedStatistics(boolean isNeedStatistics) {
        this.isNeedStatistics = isNeedStatistics;
    }

    /**
     * 子类如果想要设置自己的布局，用自己的webview的则重写此方法,返回自己布局中的WebView
     */
    protected WebView setMyWebView() {
        return null;
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        LogInfo.log("wlx", "LetvBaseWebViewActivity onCreate");
        super.onCreate(savedInstanceState);

        netType = NetworkUtils.getNetworkType(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        mNetWorkBroadcastReceiver = new NetWorkBroadcastReceiver();
        registerReceiver(mNetWorkBroadcastReceiver, intentFilter);
        setContentView(R.layout.letv_webview_new);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        if (!TextUtils.isEmpty(getIntent().getStringExtra("loadType"))) {
            loadType = getIntent().getStringExtra("loadType");// title
        }
        if (!TextUtils.isEmpty(getIntent().getStringExtra("url"))) {
            baseUrl = getIntent().getStringExtra("url");
        }
        String tempUrl = setBaseUrl();
        if (!TextUtils.isEmpty(tempUrl)) {
            baseUrl = tempUrl;
        }
        baseUrl = getValidUrl(baseUrl);
        if (TextUtils.isEmpty(baseUrl)) {
            return;
        }
        LogInfo.log("wlx", "baseUrl：" + baseUrl);
        findView();
        initWebView();
        statisticsIfNeed();// 是否需要统计，若需要则要对baseUrl做处理 登录先不加
        initView();
        flag = true;
        setCookie();
        loadUrl();
    }

    private void loadUrl() {
        if (isNeedLogin()) {
//            LetvLoginActivity.launch(this, goToLoginPageForMatchUrl, goToLoginPageForMatchUrl);
        } else {
            loadUrlOrSyncUserState();
        }
    }

    /**
     * 需要跳转到登陆
     */
    private boolean isNeedLogin() {
        return (baseUrl.startsWith("http://sso.letv.com/user/mLoginMini") || baseUrl
                .startsWith("http://sso.letv.com/user/mloginHome")) && !PreferencesManager.getInstance().isLogin();
    }

    private void setCookie() {
        CookieManager cookieManager = CookieManager.getInstance();
        LetvUtils.setCookies(this, baseUrl);// setCookie操作一定要放在initWebView之后，不然cookie会失效！
        LogInfo.log("wlx", "setCookies之后  baseCookie: " + cookieManager.getCookie(baseUrl));
    }

    private void initView() {
        urlTitleView.setText("由  " + getUrlTitle(baseUrl) + " 提供");
        pullDownUrlText.setText("由  " + getUrlTitle(baseUrl) + " 提供");
        getMoreImg.setOnClickListener(this);
        close.setOnClickListener(this);
        back_iv.setOnClickListener(this);
        titleView.setText(loadType);
        root.setRefreshData(new PublicLoadLayout.RefreshData() {
            @Override
            public void refreshData() {
                refresh();
            }
        });
    }

    /**
     * 获取网页标题栏
     * 
     * @return 标题栏
     */
    public View getTopBar() {
        return topBar;
    }

    // 第一次进入webview并且没有同步过登录登出状态的情况下同步登陆状态！！！
    protected void syncUserState() {
        flag = true;
        SyncUserStateUtil.getUserStateUtil((new SyncUserStateUtil.GetUserloginStateListener() {
            @Override
            public void onSyncSuccessed() {
                new Handler(getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        flag = true;
                        mFlagErrorpagebycookie = false;
                        LogInfo.log("wlx", "开始加载url");
                        loadUrlBySync(baseUrl);
                    }
                });
            }

            @Override
            public void onSyncFailed() {
                new Handler(getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        LogInfo.log("wlx", "同步失败，显示错误页面！");
                        mFlagErrorpagebycookie = true;
                        showErrorPage();
                        loadUrlBySync(baseUrl);
                    }
                });
            }
        })).syncUserStateByAsync(this);
        progressBar.setProgress(10);
    }

    public void setBaseUrl(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public String getBaseUrl() {
        return baseUrl;
    }

    /**
     * 模板方法
     * 如果子类要特别设置BaseUrl，复写此方法
     * 
     * @return
     */
    protected String setBaseUrl() {
        return "";
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    private String getValidUrl(String baseUrl) {
        String validUrl = baseUrl;
        if (baseUrl != null && !"".equals(baseUrl)) {
            if (!baseUrl.startsWith("http://")) {
                validUrl = "http://" + baseUrl;
            }
        }
        return validUrl;
    }

    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == goToLoginPageForJS || requestCode == goToLoginPageForMatchUrl) {
            SyncUserStateUtil.getUserStateUtil(new SyncUserStateUtil.GetUserloginStateListener() {
                @Override
                public void onSyncSuccessed() {
                    LogInfo.log("wlx", "同步成功！");
                    if (requestCode == goToLoginPageForJS) {
//                        JSBridgeUtil.getInstance().loginCallBack(true);// 把User信息传给JS并刷新页面
                    } else if (requestCode == goToLoginPageForMatchUrl) {
                        if (resultCode == Login_OK) {
                            loadUrlBySync(baseUrl);
                        } else {
                            finish();
                        }
                    }
                }

                @Override
                public void onSyncFailed() {
                    LogInfo.log("wlx", "同步失败，显示错误页面！");
                    mFlagErrorpagebycookie = true;
                    showErrorPage();
                }
            }).syncUserStateByAsync(this);
        }

//        if (InviteShareFragment.onFragmentResult != null) {
//            InviteShareFragment.onFragmentResult.onFragmentResult_back(requestCode, resultCode, data);
//        }
//
//        if (SignShareFragment.onFragmentResult != null) {
//            SignShareFragment.onFragmentResult.onFragmentResult_back(requestCode, resultCode, data);
//        }
//        if (WebShareFragment.onFragmentResult != null) {
//            WebShareFragment.onFragmentResult.onFragmentResult_back(requestCode, resultCode, data);
//        }
    }

    /**
     * 子类可用此方法来获取webview对象
     */
    protected WebView getWebView() {
        return mWebView;
    }

    protected void initWebView() {
        WebView childWebView = setMyWebView();
        if (childWebView != null) {
            mWebView = childWebView;
        }
        initSetting(mWebView, mActivity);
        if (webChromeClient == null) {
            webChromeClient = new LetvWebViewChromeClient(this);
        }
        mWebView.setWebChromeClient(webChromeClient);// *** 主要是WebViewClient的逻辑各不一样,WebChromeClient里的业务逻辑是一样的
        JSBridgeUtil.getInstance().setJSBridge(this, mWebView, handler, root);// 设置具有与JS交互的能力
    }

    public void initSetting(WebView webView, Context context) {
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setUserAgentString(LetvUtils.createUA(context,webView.getSettings().getUserAgentString()));
        webView.setVerticalScrollBarEnabled(true);
        webView.setHorizontalScrollBarEnabled(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);
    }

    protected String getUrlTitle(String url) {
        if (TextUtils.isEmpty(url)) {
            return "";
        } else {
            if (url.contains("http://")) {
                String redirectFlag = "to=http%3A%2F%2F";
                if (url.contains(redirectFlag)) {// 包含“to=http%3A%2F%2F”表示是重定向
                    url = url.substring(url.indexOf(redirectFlag) + redirectFlag.length());
                    if (url.contains("%2F")) {// "%2F"是/的转义符
                        url = url.substring(0, url.indexOf("%2F"));
                    }
                } else {
                    url = url.replace("http://", "");
                    if (url.contains("/")) {
                        int end = url.indexOf("/");
                        url = (String) url.subSequence(0, end);
                    } else if (url.contains("?")) {
                        int end = url.indexOf("?");
                        url = (String) url.subSequence(0, end);
                    }
                }
            } else {
                if (url.length() > 15) {
                    url = url.substring(0, 15);
                }
            }
            return url;
        }
    }

    private void findView() {
        getMoreImg = (ImageView) findViewById(R.id.get_more);
        titleView = (TextView) findViewById(R.id.letv_webview_title);
        urlTitleView = (TextView) findViewById(R.id.webview_title_url);
        close = (ImageView) findViewById(R.id.close_iv);
        back_iv = (ImageView) findViewById(R.id.back_iv);
        LinearLayout rootLayout = (LinearLayout) findViewById(R.id.root_layout);
        root = new PublicLoadLayout(this);
        root.addContent(R.layout.letv_webview_only);
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        rootLayout.addView(root, params);
        mWebView = (WebView) (root.findViewById(R.id.webView));
        progressBar = (ProgressBar) findViewById(R.id.loading_progress);
        pullDownUrlText = (TextView) findViewById(R.id.pulldown_title_url);
        topBar = findViewById(R.id.web_view_top_layout);
    }

    protected synchronized void loadUrlBySync(String url) {
        LogInfo.log("wlx", "loadUrlBySync url: " + url);
        if (mWebView != null) {
            if (!TextUtils.isEmpty(url) && url.contains("next_action=")) {
                try {
                    baseUrl = url.substring(url.indexOf("next_action=") + "next_action=".length());
                    String decode_baseUrl = URLDecoder.decode(baseUrl, "UTF-8");
                    mWebView.loadUrl(decode_baseUrl);
                    baseUrl = decode_baseUrl;
                    LogInfo.log("wlx", "next_action_url: " + baseUrl);
                    LogInfo.log("wlx", "decoder next_action_url: " + decode_baseUrl);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    showErrorPage();
                }
            } else {
                LogInfo.log("wlx", "mWebView.loadUrl(url)");
                progressBar.setVisibility(View.VISIBLE);
                progressBar.setProgress(10);
                mWebView.loadUrl(url);
            }
        }
    }

    private void statisticsIfNeed() {
        if (!isNeedStatistics) {
            return;
        }
        if (baseUrl != null && baseUrl.contains("letv.com") && !baseUrl.contains("ref=") && baseUrl.contains("?")) {
            baseUrl += "&ref=0101";
        } else if (baseUrl != null && baseUrl.contains("letv.com") && !baseUrl.contains("ref=")
                && !baseUrl.contains("?")) {
            baseUrl += "?ref=0101";
        }
    }

    private void showErrorPage() {
        flag = false;
        root.netError(false);
        urlTitleView.setVisibility(View.GONE);
        progressBar.setVisibility(View.GONE);
    }

    public String getShareDefaultIcon() {
        return mShareDefaultIcon;
    }

    public String getShareDefaultTitle() {
        return mShareDefaultTitle;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.close_iv) {
            finish();
        }
        else if (id == R.id.back_iv) {
            if (mWebView.canGoBack()) {
                LogInfo.log("+-->", "按下返回值之前的url：" + mWebView.getUrl());
                LogInfo.log("+-->", "LetvBaseWebView---- cangoback");

                LogInfo.log("+-->", "按下返回值之前的url：" + mWebView.getUrl());
                WebBackForwardList list = mWebView.copyBackForwardList();
                if (list.getCurrentIndex() <= 0) {
                    urlTitleView.setText("由  " + getUrlTitle(list.getItemAtIndex(0).getUrl()) + " 提供");
                    pullDownUrlText.setText("由  " + getUrlTitle(list.getItemAtIndex(0).getUrl()) + " 提供");
                } else {
                    urlTitleView.setText("由  "
                            + getUrlTitle(list.getItemAtIndex(list.getCurrentIndex() - 1).getUrl()) + " 提供");
                    pullDownUrlText.setText("由  "
                            + getUrlTitle(list.getItemAtIndex(list.getCurrentIndex() - 1).getUrl()) + " 提供");
                }
                mWebView.goBack();
                if (!close.isShown()) {
                    close.setVisibility(View.VISIBLE);
                }
            } else {
                // add zhudeshuai:添加三方调起h5的返回逻辑
                if (getIntent().getIntExtra("from", -1) == PlayConstant.LAUNCH_FROM_MSITE) {
                    // LetvSdkPlayerLibs.getInstance().exitProcess(this);
                } else {
                    finish();
                }
            }
        }
        else if (id == R.id.get_more) {
            onShareDialogShow(null);
        }
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    protected void onDestroy() {
        super.onDestroy();
        JSBridgeUtil.getInstance().unRegisterAllObservers();
        unregisterReceiver(mNetWorkBroadcastReceiver);
        try {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
            isFinish = true;
            if (mWebView != null) {

                ViewGroup vg = (ViewGroup) mWebView.getParent();
                if (vg != null) {
                    vg.removeView(mWebView);
                }
                mWebView.stopLoading();
                /**
                 * 3.0以上系统编译，如果不隐藏webview会出现崩溃
                 */
                mWebView.setVisibility(View.GONE);
                mWebView.removeAllViews();
                /**
                 * 该处的处理尤为重要:
                 * 应该在内置缩放控件消失以后,再执行mWebView.destroy()
                 * 否则报错WindowLeaked
                 */
                long timeout = ViewConfiguration.getZoomControlsTimeout();
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        new Handler(getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                mWebView.destroy();
                                mWebView = null;
                            }
                        });
                    }
                }, timeout);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getActivityName() {
        return this.getClass().getSimpleName();
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 解决出现view缓存问题
        mWebView.clearCache(true);
        mWebView.destroyDrawingCache();
        mWebView.setWillNotCacheDrawing(true);
        isFinish = false;
        callHiddenWebViewMethod("onResume");
    }

    @Override
    protected void onPause() {
//        if (shareDialogFragment != null && shareDialogFragment.isAdded()) {
//            FragmentTransaction tx = this.getSupportFragmentManager().beginTransaction();
//            tx.remove(shareDialogFragment);
//            tx.commit();
//        }
//        if (mShareNewFragment != null && mShareNewFragment.isAdded()) {
//            FragmentTransaction tx = this.getSupportFragmentManager().beginTransaction();
//            tx.remove(mShareNewFragment);
//            tx.commit();
//        }
        this.getSupportFragmentManager().executePendingTransactions();
        super.onPause();
        callHiddenWebViewMethod("onPause");
    }

    private void callHiddenWebViewMethod(String name) {
        if (mWebView != null) {
            try {
                Method method = WebView.class.getMethod(name);
                method.invoke(mWebView);
            } catch (Exception e) {
                LogInfo.log("wlx", e.getMessage());
            }
        }
    }

    // /**
    // * 分享框
    // */
    // private HalfPlaySharePopwindow mHalfPlaySharePopwindow = null;
//    public void onJsShareDialogShow(String jsonString) {
//        FragmentManager fm = this.getSupportFragmentManager();
//        if (fm != null) {
//            FragmentTransaction ft = fm.beginTransaction();
//            // ft.addToBackStack(null);
//
////            if (shareDialogFragment == null) {
////                shareDialogFragment = new InviteShareFragment();
////            } else {
////                ft.remove(shareDialogFragment);
////            }
////            shareDialogFragment.setShareText(jsonString);
////            ft.add(shareDialogFragment, "shareDialogs");
//            ft.commitAllowingStateLoss();
//        }
//        // if (mHalfPlaySharePopwindow == null) {
//        // ShareUtils.RequestShareLink(mContext);
//        // mHalfPlaySharePopwindow = new HalfPlaySharePopwindow(getActivity(), HalfPlaySharePopwindow.SHARE_FROM_TOPIC,
//        // this);
//        // mHalfPlaySharePopwindow.showPopupWindow(findViewById(R.id.root_layout));
//        // mHalfPlaySharePopwindow.setOnDismissListener(new OnDismissListener() {
//        //
//        // @Override
//        // public void onDismiss() {
//        // mHalfPlaySharePopwindow = null;
//        // }
//        // });
//        // }
//    }

    /**
     * 调起分享界面
     * 
     * @param jsonString JS传入的参数
     */
    public void onShareDialogShow(String jsonString) {
        FragmentManager fm = getSupportFragmentManager();
        if (fm != null) {
            FragmentTransaction ft = fm.beginTransaction();
//            if (mShareNewFragment == null) {
//                mShareNewFragment = new WebShareFragment(new RefreshBtnClick() {
//                    @Override
//                    public void onRefreshBtnClick() {
//                        refresh();
//                    }
//                });
//            } else {
//                ft.remove(mShareNewFragment);
//            }
//            mShareNewFragment.setDefaultShareText(this);
//            ft.add(mShareNewFragment, "shareDialog");
//            mShareNewFragment.setBaseURL(baseUrl);
//            mShareNewFragment.setIsLoadComplete(loadFinish);
//            mShareNewFragment.notifyShareLayout();
            ft.commitAllowingStateLoss();
        }
    }

    /**
     * 判断是否需要同步状态，若需要则同步，否者直接loadUrl
     */
    private void loadUrlOrSyncUserState() {
        if (!NetworkUtils.isNetworkAvailable(mContext)) {
            showErrorPage();
            return;
        }
        if (SyncUserStateUtil.isNeedSyncUserState()) {
            syncUserState();
        } else {
            loadUrlBySync(baseUrl);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
//        if (mShareNewFragment != null && mShareNewFragment.getShowsDialog()) {
//            try {
//                mShareNewFragment.dismissAllowingStateLoss();
//            } catch (Exception e) {
//            }
//            this.finish();
//        }
    }

//    public void parseShareJson(String jsonString) {
////        if (mShareNewFragment == null) {
////            mShareNewFragment = new WebShareFragment(new RefreshBtnClick() {
////
////                @Override
////                public void onRefreshBtnClick() {
////                    refresh();
////                }
////            });
////        }
////        mShareNewFragment.setJsonShareText(jsonString);
//    }

    private void refresh() {
        LogInfo.log("wlx", "刷新");
        if (!SyncUserStateUtil.isSyncUserStateSuccessWithH5() && mFlagErrorpagebycookie) {
            progressBar.setVisibility(View.GONE);
            progressBar.setVisibility(View.VISIBLE);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    progressBar.setProgress(10);
                }
            }, 50);
            LogInfo.log("wlx", "错误页面刷新加载url");
            syncUserState();
        } else {
            flag = true;
            if (TextUtils.isEmpty(mWebView.getUrl())) {
                mWebView.loadUrl(baseUrl);
            } else {
                mWebView.reload();
            }
        }
    }

    /**
     * 判断网页是否正在加载
     *
     * @return
     */
    public boolean isLoading() {
        return true;
    }
}
